// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  try {
    const { action } = event

    switch (action) {
      // 发布失物/招领
      case 'publish':
        return await publishLostFound(event, wxContext)
      
      // 获取失物招领列表
      case 'getList':
        return await getLostFoundList(event, wxContext)
      
      // 获取失物招领详情
      case 'getDetail':
        return await getLostFoundDetail(event, wxContext)
      
      // 更新失物招领
      case 'update':
        return await updateLostFound(event, wxContext)
      
      // 删除失物招领
      case 'delete':
        return await deleteLostFound(event, wxContext)
      
      // 标记已找到
      case 'markFound':
        return await markFound(event, wxContext)
      
      // 更新状态
      case 'updateStatus':
        return await updateLostFoundStatus(event, wxContext)
      
      // 搜索失物招领
      case 'search':
        return await searchLostFound(event, wxContext)
      
      // 增加浏览量
      case 'addViewCount':
        return await addViewCount(event, wxContext)
      
      default:
        return {
          code: -1,
          msg: '无效的action参数'
        }
    }
  } catch (err) {
    console.error(err)
    return {
      code: -1,
      msg: '服务器错误',
      error: err
    }
  }
}

/**
 * 发布失物/招领
 */
async function publishLostFound(event, wxContext) {
  const { OPENID } = wxContext
  const { type, item_name, category, time, location, description, images, urgency, contact_wechat, contact_qq, contact_phone, qrcode_image } = event

  try {
    const result = await db.collection('lost_found').add({
      data: {
        openid: OPENID,
        type, // 1-失物 2-招领
        item_name,
        category,
        time: new Date(time),
        location,
        description,
        images: images || [],
        urgency: urgency || 0, // 0-普通 1-紧急
        contact_wechat,
        contact_qq: contact_qq || '',
        contact_phone: contact_phone || '',
        qrcode_image: qrcode_image || '',
        status: 1, // 1-寻找中 2-已找到
        view_count: 0,
        created_at: new Date(),
        updated_at: new Date()
      }
    })

    return {
      code: 0,
      msg: '发布成功',
      data: {
        id: result._id
      }
    }
  } catch (err) {
    console.error('发布失物招领失败：', err)
    return {
      code: -1,
      msg: '发布失败',
      error: err
    }
  }
}

/**
 * 获取失物招领列表
 */
async function getLostFoundList(event, wxContext) {
  const { page = 1, pageSize = 20, type, category, location, urgency, status = 1 } = event

  try {
    const skip = (page - 1) * pageSize
    let where = { status }

    // 类型筛选
    if (type) {
      where.type = type
    }

    // 分类筛选
    if (category) {
      where.category = category
    }

    // 地点筛选
    if (location) {
      where.location = location
    }

    // 紧急程度筛选
    if (urgency !== undefined) {
      where.urgency = urgency
    }

    const result = await db.collection('lost_found')
      .where(where)
      .orderBy('urgency', 'desc') // 紧急的优先
      .orderBy('created_at', 'desc')
      .skip(skip)
      .limit(pageSize)
      .get()

    // 判断是否还有更多数据
    const hasMore = result.data.length >= pageSize

    return {
      code: 0,
      msg: '获取成功',
      data: {
        list: result.data,
        hasMore: hasMore
      }
    }
  } catch (err) {
    console.error('获取失物招领列表失败：', err)
    return {
      code: -1,
      msg: '获取失败',
      error: err
    }
  }
}

/**
 * 获取失物招领详情
 */
async function getLostFoundDetail(event, wxContext) {
  const { id } = event

  try {
    const result = await db.collection('lost_found').doc(id).get()

    if (!result.data) {
      return {
        code: -1,
        msg: '信息不存在'
      }
    }

    return {
      code: 0,
      msg: '获取成功',
      data: result.data
    }
  } catch (err) {
    console.error('获取失物招领详情失败：', err)
    return {
      code: -1,
      msg: '获取失败',
      error: err
    }
  }
}

/**
 * 更新失物招领
 */
async function updateLostFound(event, wxContext) {
  const { OPENID } = wxContext
  const { id, ...updateData } = event

  try {
    // 验证权限
    const lostFound = await db.collection('lost_found').doc(id).get()
    if (lostFound.data.openid !== OPENID) {
      return {
        code: -1,
        msg: '无权限修改'
      }
    }

    delete updateData.action
    updateData.updated_at = new Date()

    await db.collection('lost_found').doc(id).update({
      data: updateData
    })

    return {
      code: 0,
      msg: '更新成功'
    }
  } catch (err) {
    console.error('更新失物招领失败：', err)
    return {
      code: -1,
      msg: '更新失败',
      error: err
    }
  }
}

/**
 * 删除失物招领
 */
async function deleteLostFound(event, wxContext) {
  const { OPENID } = wxContext
  const { id } = event

  try {
    // 验证权限
    const lostFound = await db.collection('lost_found').doc(id).get()
    if (lostFound.data.openid !== OPENID) {
      return {
        code: -1,
        msg: '无权限删除'
      }
    }

    // 删除失物招领记录
    await db.collection('lost_found').doc(id).remove()

    // 删除所有相关的收藏记录
    try {
      await db.collection('favorites')
        .where({
          item_type: 2, // 2-失物招领
          item_id: id
        })
        .remove()
      console.log('已删除失物招领相关的收藏记录')
    } catch (err) {
      console.error('删除收藏记录失败：', err)
      // 即使删除收藏失败，也不影响失物招领删除
    }

    return {
      code: 0,
      msg: '删除成功'
    }
  } catch (err) {
    console.error('删除失物招领失败：', err)
    return {
      code: -1,
      msg: '删除失败',
      error: err
    }
  }
}

/**
 * 标记已找到
 */
async function markFound(event, wxContext) {
  const { OPENID } = wxContext
  const { id } = event

  try {
    // 验证权限
    const lostFound = await db.collection('lost_found').doc(id).get()
    if (lostFound.data.openid !== OPENID) {
      return {
        code: -1,
        msg: '无权限操作'
      }
    }

    await db.collection('lost_found').doc(id).update({
      data: {
        status: 2, // 已找到
        updated_at: new Date()
      }
    })

    return {
      code: 0,
      msg: '标记成功'
    }
  } catch (err) {
    console.error('标记失败：', err)
    return {
      code: -1,
      msg: '标记失败',
      error: err
    }
  }
}

/**
 * 搜索失物招领（简化版 - 只搜索物品名称）
 */
async function searchLostFound(event, wxContext) {
  const { keyword, page = 1, pageSize = 20, type, category, sort = 'latest' } = event

  try {
    const skip = (page - 1) * pageSize
    
    console.log('搜索参数：', { keyword, page, pageSize, type, category, sort })
    
    // 构建查询条件 - 先用最简单的方式
    let where = {
      status: 1,
      item_name: new RegExp(keyword, 'i')  // 使用原生 RegExp
    }
    
    if (type) {
      where.type = type
    }
    
    if (category) {
      where.category = category
    }

    console.log('查询条件：', where)

    // 排序
    let orderBy = 'created_at'
    let order = 'desc'
    if (sort === 'urgent') {
      orderBy = 'urgency'
      order = 'desc'
    }

    const result = await db.collection('lost_found')
      .where(where)
      .orderBy(orderBy, order)
      .skip(skip)
      .limit(pageSize)
      .get()

    console.log('搜索结果数量：', result.data.length)

    // 判断是否还有更多数据
    const hasMore = result.data.length >= pageSize

    return {
      code: 0,
      msg: '搜索成功',
      data: {
        list: result.data,
        hasMore: hasMore,
        total: result.data.length
      }
    }
  } catch (err) {
    console.error('搜索失物招领失败：', err)
    return {
      code: -1,
      msg: '搜索失败',
      error: err.toString()
    }
  }
}

/**
 * 更新失物招领状态
 */
async function updateLostFoundStatus(event, wxContext) {
  const { OPENID } = wxContext
  const { id, status } = event

  try {
    // 验证权限
    const lostFound = await db.collection('lost_found').doc(id).get()
    if (!lostFound.data) {
      return {
        code: -1,
        msg: '失物招领不存在'
      }
    }

    if (lostFound.data.openid !== OPENID) {
      return {
        code: -1,
        msg: '无权限操作'
      }
    }

    await db.collection('lost_found').doc(id).update({
      data: {
        status: status,
        updated_at: new Date()
      }
    })

    return {
      code: 0,
      msg: '更新成功'
    }
  } catch (err) {
    console.error('更新状态失败：', err)
    return {
      code: -1,
      msg: '更新失败',
      error: err
    }
  }
}

/**
 * 增加浏览量
 */
async function addViewCount(event, wxContext) {
  const { id } = event

  try {
    await db.collection('lost_found').doc(id).update({
      data: {
        view_count: _.inc(1)
      }
    })

    return {
      code: 0,
      msg: '成功'
    }
  } catch (err) {
    console.error('增加浏览量失败：', err)
    return {
      code: -1,
      msg: '失败',
      error: err
    }
  }
}

